package com.hanlink.dsp.util;

import android.app.Dialog;
import android.content.Context;
import android.hardware.input.InputManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.DrawableRes;

import com.blankj.utilcode.util.SPUtils;
import com.edge.pbx.view.PbxCircleRadioSeekBar;
import com.edge.pbx.view.common.ChNameRadioView;
import com.edge.pbx.view.summing.PbxOutputSelectChannelView;
import com.edge.pbx.view.summing.PbxOutputSelectChannelsLayout;
import com.edge.pbxdsp.R;
import com.hanlink.dsp.DspContext;
import com.hanlink.dsp.DspSettings;

import com.hanlink.dsp.ca.model.channel.SummingChannel;
import com.hanlink.dsp.ca.model.settings.SummingSettings;
import com.hanlink.dsp.ui.fragment.Summing3Fragment;
import com.qztech.utils.YzDebug;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import static com.hanlink.dsp.util.DataUtil.KEY_CHANNEL_NAME;
import static com.hanlink.dsp.util.DataUtil.KEY_INPUT;

/**
 * Created by zhb on 2017/11/6.
 */

public class ViewUtil {

    private static Toast mToast;

    public static void toast(Context context, String text) {
        if (mToast != null)
            mToast.cancel();
        mToast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
        mToast.show();
    }


    public interface OnObjectCallback<T> {
        void onCallback(T object);
    }

    public static void showQValueInputDialog(Context context, OnObjectCallback<Integer> callback) {
        showInputDialog(context, "Please input", " 5 ~ 2000 ", callback);
    }

    public static void showFreqInputDialog(Context context, OnObjectCallback<Integer> callback) {
        showInputDialog(context, "Please input", " 20 ~ 20000 ", callback);
    }

    private static void showInputDialog(Context context, String title, String hint, OnObjectCallback<Integer> callback) {
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(context, com.qztech.sdk.R.style.dialog);
        final View view = LayoutInflater.from(context).inflate(R.layout.dialog_change_channel_name, null, false);
        final EditText et = view.findViewById(R.id.et);
        androidx.appcompat.app.AlertDialog alertDialog = builder.setView(view)
//                .setTitle(R.string.title_change_password)
                .setCancelable(false)
                .create();
        et.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        et.setHint(hint);
        ((TextView) view.findViewById(R.id.name)).setText("Value:");
        ((TextView) view.findViewById(R.id.title)).setText(title);
        view.findViewById(R.id.ok).setOnClickListener(v -> {
            final String text = et.getText().toString().trim();
            if (TextUtils.isEmpty(text)) {
                toast(context, "The input cannot be empty");
                return;
            }
            int ret = 0;
            try {
                ret = Integer.parseInt(text);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (callback != null) {
                callback.onCallback(ret);
            }
            alertDialog.dismiss();
        });
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.show();

        et.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            final InputMethodManager imm;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                imm = context.getSystemService(InputMethodManager.class);
                if (imm != null) {
                    et.requestFocus();
                    imm.showSoftInput(et, InputMethodManager.SHOW_FORCED);
                }
            }

        });


    }

    public static void initChannelName(List<PbxOutputSelectChannelView> tvs) {
        if (tvs == null) return;
        int index = 0;
        for (PbxOutputSelectChannelView tv : tvs) {
            final String saveName = SPUtils.getInstance(Context.MODE_PRIVATE).getString(KEY_CHANNEL_NAME + index, null);
            if (!TextUtils.isEmpty(saveName))
                tv.setName(saveName);
            index++;
        }

    }

    public static void initChannelNames(List<PbxCircleRadioSeekBar> tvs) {
        if (tvs == null) return;
        int index = 0;
        for (PbxCircleRadioSeekBar tv : tvs) {
            String saveName = SPUtils.getInstance(Context.MODE_PRIVATE).getString(KEY_CHANNEL_NAME + index, null);
            if (TextUtils.isEmpty(saveName)) {
                saveName = "CH " + (index + 1);
            }
            tv.setTitle(saveName);
            index++;
        }

    }

    public static void initChannelName(List<PbxOutputSelectChannelView> tvs, ChNameRadioView[] crvs) {
        if (tvs == null) return;
        int index = 0;
        SPUtils sp = SPUtils.getInstance(Context.MODE_PRIVATE);
        for (int i = 0; i < 4; i++) {
            String name1 = sp.getString(KEY_CHANNEL_NAME + (i * 2), null);
            String name2 = sp.getString(KEY_CHANNEL_NAME + (i * 2 + 1), null);
            if (TextUtils.isEmpty(name1)) {
                name1 = "CH " + (i * 2 + 1);
            } else {
                tvs.get(i * 2).setName(name1);
            }
            if (TextUtils.isEmpty(name2)) {
                name2 = "CH " + (i * 2 + 2);
            } else {
                tvs.get(i * 2 + 1).setName(name2);
            }
            crvs[i].setTopName(name1);
            crvs[i].setBottomName(name2);
        }
        for (PbxOutputSelectChannelView tv : tvs) {
            final String saveName = sp.getString(KEY_CHANNEL_NAME + index, null);
            if (!TextUtils.isEmpty(saveName))
                tv.setName(saveName);

            index++;
        }
    }

    public static void initChannelName(TextView[] tvs) {
        if (tvs == null) return;
        int index = 0;
        for (TextView tv : tvs) {
            final String saveName = SPUtils.getInstance(Context.MODE_PRIVATE).getString(KEY_CHANNEL_NAME + index, null);
            if (!TextUtils.isEmpty(saveName))
                tv.setText(saveName);
            index++;
        }

    }

    public static void showChangeInputDialog(Context context, int channel, OnObjectCallback<String> callback) {
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(context, com.qztech.sdk.R.style.dialog);
        final View view = LayoutInflater.from(context).inflate(R.layout.dialog_change_channel_name, null, false);
        final EditText et = view.findViewById(R.id.et);
        androidx.appcompat.app.AlertDialog alertDialog = builder.setView(view)
//                .setTitle(R.string.title_change_password)
                .setCancelable(false)
                .create();

        view.findViewById(R.id.ok).setOnClickListener(v -> {
            final String text = et.getText().toString().trim();
            if (TextUtils.isEmpty(text)) {
                toast(context, "The name cannot be empty");
                return;
            }
            if (text.length() > 6) {
                toast(context, "Maximum 6 Characters");
                return;
            }
            SPUtils.getInstance(Context.MODE_PRIVATE).put(KEY_INPUT + channel, text);
            if (callback != null) {
                callback.onCallback(text);
            }
            alertDialog.dismiss();
        });
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.show();

        view.findViewById(R.id.et).requestFocus();
    }

    public static void showChangeChannelNameDialog(Context context, int channel, OnObjectCallback<String> callback) {
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(context, com.qztech.sdk.R.style.dialog);
        final View view = LayoutInflater.from(context).inflate(R.layout.dialog_change_channel_name, null, false);
        final EditText et = view.findViewById(R.id.et);
        androidx.appcompat.app.AlertDialog alertDialog = builder.setView(view)
//                .setTitle(R.string.title_change_password)
                .setCancelable(false)
                .create();

        view.findViewById(R.id.ok).setOnClickListener(v -> {
            final String text = et.getText().toString().trim();
            if (TextUtils.isEmpty(text)) {
                toast(context, "The name cannot be empty");
                return;
            }
            if (text.length() > 6) {
                toast(context, "Maximum 6 Characters");
                return;
            }
            SPUtils.getInstance(Context.MODE_PRIVATE).put(KEY_CHANNEL_NAME + channel, text);
            if (callback != null) {
                callback.onCallback(text);
            }
            alertDialog.dismiss();
        });
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.show();

        view.findViewById(R.id.et).requestFocus();
    }

    public static void setEnabled(View view, boolean enabled) {
        if (null == view) {
            return;
        }
        if (view instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) view;
            LinkedList<ViewGroup> queue = new LinkedList<ViewGroup>();
            queue.add(viewGroup);
            // 遍历viewGroup
            while (!queue.isEmpty()) {
                ViewGroup current = queue.removeFirst();
                current.setEnabled(enabled);
                for (int i = 0; i < current.getChildCount(); i++) {
                    if (current.getChildAt(i) instanceof ViewGroup) {
                        queue.addLast((ViewGroup) current.getChildAt(i));
                    } else {
                        current.getChildAt(i).setEnabled(enabled);
                    }
                }
            }
        } else {
            view.setEnabled(enabled);
        }
    }

    public static void resizeDialogWidth(Dialog dialog, float widthPrecentage) {
        resizeDialogWidthHeight(dialog, widthPrecentage, Float.NaN);
    }

    public static void resizeDialogHeight(Dialog dialog, float heightPrecentage) {
        resizeDialogWidthHeight(dialog, Float.NaN, heightPrecentage);
    }

    public static void resizeDialogWidthHeight(Dialog dialog, float widthPrecentage, float heightPrecentage) {
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        DisplayMetrics metrics = dialog.getContext().getResources().getDisplayMetrics();
        if (widthPrecentage != Float.NaN) {
            final int minWidth = (int) (metrics.widthPixels * widthPrecentage);
            if (lp.width < minWidth) {
                lp.width = minWidth;
                dialog.getWindow().setAttributes(lp);
            }
        }
        if (heightPrecentage != Float.NaN) {
            final int minHeight = (int) (metrics.heightPixels * heightPrecentage);
            if (lp.height < minHeight) {
                lp.height = minHeight;

            }
        }
        dialog.getWindow().setAttributes(lp);
    }


    public static void initOutputChannels(SummingSettings summingSettings, List<PbxOutputSelectChannelView> views) {
        List<SummingChannel> channels = summingSettings.getSummingChannels();
        PbxOutputSelectChannelView view;
        for (int i = 0, len = Math.min(channels.size(), views.size()); i < len; i++) {
            view = views.get(i);
            view.initSums(channels.get(i).getHigh_input_channels());
//            YzDebug.d("Yang" ,"  initOutputChannels:" + i +" " + Arrays.toString(channels.get(i).getHigh_input_channels()));
        }
    }

    public static void findOutputViews(List<PbxOutputSelectChannelView> mOutputViews, View root, PbxOutputSelectChannelView.OnCheckChangeListener listener) {
        mOutputViews.clear();
        mOutputViews.clear();
        mOutputViews.add(root.findViewById(R.id.pbx_output_select_channel1));
        mOutputViews.add(root.findViewById(R.id.pbx_output_select_channel2));
        mOutputViews.add(root.findViewById(R.id.pbx_output_select_channel3));
        mOutputViews.add(root.findViewById(R.id.pbx_output_select_channel4));
        mOutputViews.add(root.findViewById(R.id.pbx_output_select_channel5));
        mOutputViews.add(root.findViewById(R.id.pbx_output_select_channel6));
        mOutputViews.add(root.findViewById(R.id.pbx_output_select_channel7));
        mOutputViews.add(root.findViewById(R.id.pbx_output_select_channel8));
        for (PbxOutputSelectChannelView outputView : mOutputViews) {
            outputView.setOnCheckChangeListener(listener);
        }
    }

    public static void initCarType(PbxOutputSelectChannelsLayout layout) {
        if (layout == null) return;
        final int carType = DspSettings.SUMMING_SETTINGS.getCarType();
        int drawableId = View.NO_ID;
        switch (carType) {
            case Summing3Fragment.CAR_TYPE_CAR:
                final int leftRight = DspSettings.SUMMING_SETTINGS.getDriverType();
                drawableId = leftRight == 1 ? R.drawable.pbx_output_select_car_right : R.drawable.pbx_output_select_car_left;
                break;
            case Summing3Fragment.CAR_TYPE_MOTO:
                drawableId = R.drawable.pbx_output_select_moto;
                break;
            case Summing3Fragment.CAR_TYPE_UTV:
                drawableId = R.drawable.pbx_output_select_utv;
                break;
        }
        if (drawableId != View.NO_ID) {
            layout.setCarTypeDrawable(drawableId);
        }

    }
}
